﻿#region Header
// ------------------------ Licence / Copyright ------------------------
// 
// ScrumTable for Scrum Meeting Support
// Copyright © HSR - Hochschule für Technik Rapperswil
// All Rights Reserved
// 
// Author:
//  Michael Gfeller Silvan Gehrig Patrick Boos
// 
// ---------------------------------------------------------------------
#endregion

#region Usings

using System;
using System.Collections.Generic;
using System.Linq;
using ScrumTable.Common;
using ScrumTable.Common.Logging;
using ScrumTable.Common.Net;
using ScrumTable.Common.Security;
using ScrumTable.DL.Data.TFS.Properties;
using ScrumTable.DL.Data.TFS.Services.Reporting.ReportService;

#endregion

namespace ScrumTable.DL.Data.TFS.Services.Reporting
{
    /// <summary>
    /// This class contains a set of functionalities which are used to
    /// connect to the Microsoft SQL Reporting Services and its charts.
    /// </summary>
    /// <remarks>
    /// All operations on this instance will invoke the underlying RS
    /// instance.
    /// </remarks>
    public class RsContext
    {
        #region Declarations
        //--------------------------------------------------------------------
        // Declarations
        //--------------------------------------------------------------------

        ///<summary>
        /// Specifies a set of arguments which must be passed to the
        /// GetAbsolutPathFromReportPath() path in order to retrieve a valid
        /// report image.
        ///</summary>
        public const string PostCommandArguments = "rs:Command=Render&rs:Format=IMAGE";

        private readonly ConnectionInformation _connectionCtx;

        #endregion

        #region Properties
        //--------------------------------------------------------------------
        // Properties
        //--------------------------------------------------------------------

        /// <summary>
        /// Specifies the registration of the underlying Reporting Service.
        /// </summary>
        private ServiceRegistration ServiceRegistration { get; set; }

        private bool CanConnect { get { return ServiceRegistration.HasServiceUri; } }

        #endregion

        #region Constructors / Destructor
        //--------------------------------------------------------------------
        // Constructors / Destructor
        //--------------------------------------------------------------------

        /// <summary>
        /// Creates a new WssContext instance. This constructor is used in
        /// the current library only.
        /// </summary>
        public RsContext(ServiceRegistration rsService, ConnectionInformation connectionCtx)
        {
            PreCondition.AssertNotNull(rsService, "rsService");
            PreCondition.AssertNotNull(connectionCtx, "connectionCtx");

            _connectionCtx = connectionCtx;
            ServiceRegistration = rsService;
        }

        #endregion

        #region Methods
        //--------------------------------------------------------------------
        // Methods
        //--------------------------------------------------------------------

        /// <summary>
        /// Gets all reports for the given project and the credentials
        /// </summary>
        /// <returns></returns>
        public IList<CatalogItem> GetReportList()
        {
            if (CanConnect)
            {
                using (ReportingService2005 rs = GetReportingService())
                {
                    try
                    {
                        return
                            (from report in rs.ListChildren(ServiceRegistration.PortalUri.GetQueryWithoutDelimiter(), true)
                             where report.Type == ItemTypeEnum.Report
                             select report).ToList();
                    }
                    catch (Exception e)
                    {
                        Logger<RsContext>.Error(Resources.ExcRsCtxReportListError, e);
                    }
                }
            }
            return new CatalogItem[0];
        }

        /// <summary>
        /// Gets the user parameters for a catalog item (report)
        /// </summary>
        /// <param name="report"></param>
        /// <returns></returns>
        public IList<ReportParameter> GetItemParameters(CatalogItem report)
        {
            PreCondition.AssertNotNull(report, "report");

            if (CanConnect)
            {
                using (ReportingService2005 rs = GetReportingService())
                {
                    return (from parameter in rs.GetReportParameters(report.Path, null, true, null, null)
                            where parameter.PromptUser && !string.IsNullOrEmpty(parameter.Prompt)
                            select parameter).ToList();
                }
            }
            return new ReportParameter[0];
        }

        /// <summary>
        /// Gets the absolute path of the given report. This must be evaluated
        /// in conjunction with the relative query path.
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public Uri GetAbsolutPathFromReportPath(string path)
        {
            return new Uri(
                CanConnect
                    ? ServiceRegistration.PortalUri.ReplaceQuery(path).ToString()
                    : path,
                UriKind.RelativeOrAbsolute);
        }

        private ReportingService2005 GetReportingService()
        {
            return new ReportingService2005
            {
                Url = ServiceRegistration.ServiceUri.ToString(),
                Credentials = _connectionCtx.NetworkCredentials
            };
        }

        #endregion

        #region Events
        //--------------------------------------------------------------------
        // Events
        //--------------------------------------------------------------------

        #endregion
    }
}
